package com.tonann.web.app;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSONObject;
import com.tonann.app.VO.MySensor;
import com.tonann.app.domain.*;
import com.tonann.app.dto.FaultHandleDto;
import com.tonann.app.service.*;
import com.tonann.common.constant.CacheConstants;
import com.tonann.common.constant.Constants;
import com.tonann.common.core.domain.AjaxResult;
import com.tonann.common.core.domain.entity.SysDictData;
import com.tonann.common.core.domain.entity.SysMenu;
import com.tonann.common.core.domain.entity.SysPlace;
import com.tonann.common.core.domain.entity.SysUser;
import com.tonann.common.core.domain.model.LoginBody;
import com.tonann.common.utils.DateUtils;
import com.tonann.common.utils.DictUtils;
import com.tonann.common.utils.SecurityUtils;
import com.tonann.common.utils.StringUtils;
import com.tonann.framework.web.service.SysLoginService;
import com.tonann.framework.web.service.SysPermissionService;
import com.tonann.system.service.ISysDictDataService;
import com.tonann.system.service.ISysMenuService;
import com.tonann.system.service.ISysPlaceService;
import com.tonann.system.service.ISysUserService;
import com.tonann.web.vo.*;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections4.map.HashedMap;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/myapp")
public class AppLoginController {
    @Resource
    private SysLoginService loginService;

    @Resource
    private ISysMenuService menuService;

    @Resource
    private SysPermissionService permissionService;
    @Resource
    private ISysUserService userService;
    @Resource
    private IAppDeviceService deviceService;
    @Resource
    private IAppSensorService sensorService;
    @Resource
    private ISysPlaceService placeService;
    @Resource
    private IAppFaultService appFaultService;
    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private ISysUserService sysUserService;
    @Resource
    private IAppFaultService faultService;

    @Resource
    private IAppFaultRuleService faultRuleService;
    @Resource
    private IAppFaultHandleService faultHandleService;
    @Resource
    private IAppFaultHandleRecordService faultHandleRecordService;
    @Resource
    private IAppFaultReadService faultReadService;
    @Resource
    private IAppOneKeyRepairService oneKeyRepairService;
    @Resource
    private IAppDeviceDocumentService appDeviceDocumentService;
    @Resource
    private ISysPlaceService sysPlaceService;

    @Resource
    private ISysDictDataService sysDictDataService;

    @Resource
    private IAppProjectService appProjectService;

    /**
     * 登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody) {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }
    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    public AjaxResult getInfo() {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("sysUser", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters() {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }

    /**
     * 获取设备类型
     */
    @GetMapping("/dictData")
    public AjaxResult getDictData() {
        SysDictData sysDictData = new SysDictData();
        sysDictData.setDictType("app_device_type");
        List<SysDictData> dataList = sysDictDataService.selectDictDataList(sysDictData);
        return AjaxResult.success(dataList);
    }

    @ApiOperation(value = "获取用户的设备种类")
    @GetMapping("/device/type")
    public AjaxResult getMyDeviceType() {
        String userName = SecurityUtils.getUsername();
        SysUser sysUser = userService.selectUserByUserName(userName);
        List<AppDevice> deviceList = new ArrayList<>();
        if (sysUser != null) {
            if (MySensor.getInstance().userDeviceMap.containsKey(sysUser.getUserId())){
                deviceList = MySensor.getInstance().userDeviceMap.get(sysUser.getUserId());
            }else {
                deviceList = deviceService.selectDeviceListByUserId(sysUser.getUserId());
                MySensor.getInstance().userDeviceMap.put(sysUser.getUserId(),deviceList);
            }
        } else {
            deviceList = deviceService.selectDeviceListIsShow();
        }
        List<String> deviceTypeList = new ArrayList<>();
        for (AppDevice appDevice : deviceList) {
            if (!deviceTypeList.contains(appDevice.getType())) {
                deviceTypeList.add(appDevice.getType());
            }
        }
        return AjaxResult.success(deviceTypeList);
    }

    @ApiOperation(value = "获取设备告警信息")
    @GetMapping("/device/alarm")
    public AjaxResult getMyDeviceAlarm() throws Exception {
        String userName = SecurityUtils.getUsername();
        SysUser sysUser = userService.selectUserByUserName(userName);
        List<AppDevice> deviceList = new ArrayList<>();
        List<String> alarmList = new ArrayList<>();
        if (sysUser != null) {
            if (MySensor.getInstance().userDeviceMap.containsKey(sysUser.getUserId())){
                deviceList = MySensor.getInstance().userDeviceMap.get(sysUser.getUserId());
            }else {
                deviceList = deviceService.selectDeviceListByUserId(sysUser.getUserId());
                MySensor.getInstance().userDeviceMap.put(sysUser.getUserId(),deviceList);
            }
        } else {
            deviceList = deviceService.selectDeviceListIsShow();
        }
        for (AppDevice appDevice : deviceList) {
            List<AppFault> faultList = appFaultService.selectUnCheckedAppFaultListByDeviceId(appDevice.getDeviceId());
            String alarm = "";
            Map<Long, AppFault> faultMap = new HashedMap<>();
            for (AppFault appFault : faultList) {
                AppFault fault = faultMap.get(appFault.getFaultRuleId());
                if (fault == null) {
                    faultMap.put(appFault.getFaultRuleId(), appFault);
                } else if (appFault.getCreateTime().compareTo(fault.getCreateTime()) > 0) {
                    faultMap.put(appFault.getFaultRuleId(), appFault);
                }
            }
            for (Long key : faultMap.keySet()) {
                AppFault fault = faultMap.get(key);
                if (fault != null) {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String dateStr = simpleDateFormat.format(fault.getCreateTime());
                    alarm += fault.getFaultName() + ":" + dateStr;
                    alarm = appDevice.getDeviceName() + ":" + alarm;
                    alarmList.add(alarm);
                }
            }
        }
        return AjaxResult.success(alarmList);
    }

    @ApiOperation(value = "获取用户的设备种类的列表")
    @GetMapping("/device/type/list")
    public AjaxResult getMyDeviceTypeList(String type, Integer pageNum, Integer pageSize ) throws Exception {
        String userName = SecurityUtils.getUsername();
        SysUser sysUser = userService.selectUserByUserName(userName);
        //用户的设备列表
        List<AppDevice> deviceList = new ArrayList<>();
        long start = System.currentTimeMillis();
        List<DeviceAppVO> voList = new ArrayList<>();
        if (sysUser != null) {
            if (MySensor.getInstance().userDeviceMap.containsKey(sysUser.getUserId())){
                deviceList = MySensor.getInstance().userDeviceMap.get(sysUser.getUserId());
            }else {
                deviceList = deviceService.selectDeviceListByUserId(sysUser.getUserId());
                MySensor.getInstance().userDeviceMap.put(sysUser.getUserId(),deviceList);
            }
        } else {
            deviceList = deviceService.selectDeviceListIsShow();
        }
        System.out.println("用户的设备列表耗时:" + (System.currentTimeMillis() - start));
        //赛选设备类型
        deviceList = deviceList.stream().filter(item -> item.getType().equals(type)).collect(Collectors.toList());
        List<Long> deviceIds = deviceList.stream().map(AppDevice::getDeviceId).collect(Collectors.toList());
         start = System.currentTimeMillis();
        if (!deviceIds.isEmpty()) {
            //此类设备下的所有传感器
            List<AppSensor> sensorList  = new ArrayList<>();
            String key = deviceIds.stream().map(Object::toString).collect(Collectors.joining(","));
            if (MySensor.getInstance().devicesSensorMap.get(key) != null){
                sensorList = MySensor.getInstance().devicesSensorMap.get(key);
            }else {
                sensorList = sensorService.selectAppSensorAllListByDeviceIdsForAPP(deviceIds);
                MySensor.getInstance().devicesSensorMap.put(key,sensorList);
            }
            Map<Long, List<AppSensor>> sensorListMap = new HashMap<>();
            // 传感器的内存数据值
            for (AppSensor sensor : sensorList) {
                String s = null;
                try {
                    Object object = redisTemplate.opsForValue().get(CacheConstants.APP_SENSOR_VALUE_KEY + sensor.getDeviceId() + ":sensorId:" + sensor.getSensorId());
                    if (object != null) {
                        if (object instanceof String) {
                            s = (String) object;
                        } else if (object instanceof BigDecimal) {
                            s = ((BigDecimal) object).toString();
                        } else {
                            System.out.println(object.toString());
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println(CacheConstants.APP_SENSOR_VALUE_KEY + sensor.getDeviceId() + ":sensorId:" + sensor.getSensorId());
                }
                sensor.setValue(s);
            }
            //获取选中设备的位置数据
            List<AppDevicePlaces> devicePlacesList =  deviceService.selectAppDevicePlaceListByDeviceIds(deviceIds);
            //每一个设备的位置数据做一个Map
            Map<Long,List<AppDevicePlaces>> placeMap = devicePlacesList.stream().collect(Collectors.groupingBy(AppDevicePlaces::getDeviceId));
            //获取传感器的位置的父位置
            List<Long> devicePlaceParentIdList = devicePlacesList.stream().map(item -> item.getPlace().getParentId()).collect(Collectors.toList());
            //父级位置去重
            devicePlaceParentIdList = new ArrayList<>(new HashSet<>(devicePlaceParentIdList));
            Map<Long, SysPlace> sysPlaceMap = new HashMap<>();
            if (!devicePlaceParentIdList.isEmpty()) {
                List<SysPlace> sysPlaceList = sysPlaceService.selectPlaceByIds(devicePlaceParentIdList);
                sysPlaceMap = sysPlaceList.stream().collect(Collectors.toMap(SysPlace::getPlaceId, item -> item));
            }
            sensorListMap = sensorList.stream().collect(Collectors.groupingBy(AppSensor::getDeviceId));
            System.out.println("传感器处理:" + (System.currentTimeMillis() -start));
            for (AppDevice appDevice : deviceList) {
                if (sensorListMap.get(appDevice.getDeviceId()) != null) {
                    start = System.currentTimeMillis();
                    DeviceAppVO vo = new DeviceAppVO();
                    String json = JSONObject.toJSONString(appDevice);
                    vo =  JSONObject.parseObject(json, DeviceAppVO.class);
                    AppProject  appProject = appDevice.getAppProject();
                    ProjectAppVO projectAppVO = new ProjectAppVO();
                    BeanUtils.copyProperties(projectAppVO,appProject);
                    vo.setAppProject(projectAppVO);
                    List<AppDevicePlaces> placesList = placeMap.get(appDevice.getDeviceId());
                    if (placesList != null && !placesList.isEmpty()) {
                        List<String> placeNames = new ArrayList<>();
                        for (AppDevicePlaces place : placesList){
                            SysPlace sysPlace = sysPlaceMap.get(place.getPlace().getParentId());
                            if (sysPlace != null){
                                placeNames.add(sysPlace.getPlaceName());
                            }
                        }
                        vo.setPosition(String.join(",", placeNames));
                    }
                    List<AppSensor> appSensorList = sensorListMap.get(appDevice.getDeviceId());
                    List<AppSensor> powerStatusSensorList = new ArrayList<>();
                    if (!appSensorList.isEmpty()) {
                        List<SensorAppVO> sensorAppVOList = new ArrayList<>();
                        for (AppSensor appSensor : appSensorList){
                            SensorAppVO sensorAppVO = new SensorAppVO();
                            BeanUtils.copyProperties(sensorAppVO,appSensor);
                            sensorAppVOList.add(sensorAppVO);
                        }
                        vo.setSensorList(sensorAppVOList);
                        long sensorStart = System.currentTimeMillis();
                        Map<String, List<AppSensor>> sensorTypeMap = appSensorList.stream().collect(Collectors.groupingBy(AppSensor::getSensorType));
                        for (String sensorType : sensorTypeMap.keySet()) {
                            List<AppSensor> sensorTypeList = sensorTypeMap.get(sensorType);
                            if (sensorTypeList == null || sensorTypeList.isEmpty()) {
                                continue;
                            }
                            sensorTypeList = sensorTypeList.stream().filter(item -> item.getValue() != null).collect(Collectors.toList());
                            if (sensorTypeList.isEmpty()) {
                                continue;
                            }
                            for (AppSensor appSensor : sensorTypeList) {
                                String value = appSensor.getValueDesc() != null ? appSensor.getValueDesc() : appSensor.getValue();
                                switch (sensorType) {
                                    case "4":
                                        vo.setAirVolume(value);
                                        break;
                                    case "9":
                                        vo.setAirSpeed(value);
                                        break;
                                    case "8":
                                        if (appSensor.getIsHeight() != null && appSensor.getIsHeight().equals("1")) {
                                            vo.setWindowHeight(value);
                                        }
                                        break;
                                    case "13":
                                        vo.setAngle(value);
                                        break;
                                    case "2":
                                        vo.setHumidity(value);
                                        break;
                                    case "1":
                                        if (appDevice.getType().equals("16")) {
                                            if (appSensor.getSensorName().contains("冷藏")) {
                                                vo.setColdTemperature(value);
                                            } else {
                                                vo.setTemperature(value);
                                            }
                                        } else {
                                            vo.setTemperature(value);
                                        }
                                        break;
                                    case "3":
                                        vo.setPressure(value);
                                        break;
                                    case "6":
                                        vo.setPowerConsumption(value);
                                        break;
                                    case "10":
                                        vo.setFrequency(value);
                                        break;
                                    case "11":
                                        vo.setAmpere(value);
                                        break;
                                    case "16":
                                        vo.setTvoc(value);
                                        break;
                                    case "21":
                                        vo.setCH2O(value);
                                        break;
                                    case "23":
                                        vo.setO2(value);
                                        break;
                                    case "15":
                                        vo.setNoise(value);
                                        break;
                                    case "14":
                                        vo.setIllumination(value);
                                        break;
                                    case "20":
                                        vo.setCO2(value);
                                        break;
                                    case "19":
                                        vo.setPM1(value);
                                        break;
                                    case "18":
                                        vo.setPM10(value);
                                        break;
                                    case "17":
                                        vo.setPM2Point5(value);
                                        break;
                                    case "25":
                                        vo.setRawWaterConductivity(value);
                                        break;
                                    case "26":
                                        vo.setFirstWaterConductivity(value);
                                        break;
                                    case "27":
                                        vo.setSecondWaterConductivity(value);
                                        break;
                                    case "28":
                                        vo.setLiquidLevel(value);
                                        break;
                                    case "24":
                                        powerStatusSensorList.add(appSensor);
                                        break;
                                    case "22":
                                        if (appSensor.getIsOn() != null && appSensor.getIsOn().equals("1") && vo.getPower() == null) {
                                            vo.setPower("0");
                                            vo.setIsRunning("0");
                                            vo.setIsOnline("0");
                                        }
                                        break;
                                }
                                if (appSensor.getUnit().equals("开关量")) {
                                    if (StringUtils.endsWith(value, ".0")) {
                                        value = StringUtils.substringBefore(value, ".0");
                                    }
                                    if (appSensor.getIsLight() != null && appSensor.getIsLight().equals("1")) {
                                        vo.setLight(value);
                                    } else if (appSensor.getIsForce() != null && appSensor.getIsForce().equals("1")) {
                                        vo.setForce(value);
                                    } else if (appSensor.getIsOn() != null && appSensor.getIsOn().equals("1")) {
                                        vo.setPower(value);
                                    } else if (appSensor.getIsAutoDoor() != null && appSensor.getIsAutoDoor().equals("1")) {
                                        vo.setIsAutoDoor(value);
                                    } else if (appSensor.getIsBeing() != null && appSensor.getIsBeing().equals("1")) {
                                        vo.setIsBeing(value);
                                    } else if (appSensor.getWorkMode() != null && appSensor.getWorkMode().equals("1")) {
                                        vo.setWorkingMode(value);
                                    }
                                }
                                System.out.println(appDevice.getDeviceName() + ":sensor:end:" + (System.currentTimeMillis() - sensorStart));
                            }
                        }
                        if (!powerStatusSensorList.isEmpty()) {
                            for (AppSensor sensor : powerStatusSensorList) {
                                if (sensor.getValue() != null && !sensor.getValue().trim().equals("")) {
                                    if (StringUtils.endsWith(sensor.getValue(), ".0")) {
                                        String val = StringUtils.substringBefore(sensor.getValue(), ".0");
                                        sensor.setValue(val);
                                    }
                                    vo.setPower(sensor.getValue());
                                }
                            }
                        }
                        if (!appSensorList.isEmpty()) {
                            voList.add(vo);
                        }
                        System.out.println(appDevice.getDeviceName() + ":end:" + (System.currentTimeMillis() -start));
                    }
                }
            }
        }
        if (pageNum != null && pageSize != null){
            int fromIndex = (pageNum  - 1 ) * pageSize;
            int endIndex = (pageNum) * pageSize;
            voList = voList.subList(fromIndex,endIndex);
        }
        return AjaxResult.success(voList);
    }

    @ApiOperation(value = "获取设备信息")
    @GetMapping("/device")
    public AjaxResult getDevice() throws Exception {
        String userName = SecurityUtils.getUsername();
        SysUser sysUser = userService.selectUserByUserName(userName);
        List<AppDevice> deviceList = new ArrayList<>();
        List<DeviceVO> voList = new ArrayList<>();
        if (sysUser != null) {
            deviceList = deviceService.selectDeviceListByUserId(sysUser.getUserId());
        } else {
            deviceList = deviceService.selectDeviceListIsShow();
        }
        for (AppDevice appDevice : deviceList) {
            DeviceVO vo = new DeviceVO();
            BeanUtils.copyProperties(vo, appDevice);
            List<Long> placeIds = deviceService.selectAppDevicePlaceListByDeviceId(appDevice.getDeviceId());
            StringBuilder placeName = new StringBuilder();
            for (Long placeId : placeIds) {
                SysPlace place = placeService.selectPlaceById(placeId);
                if (place != null) {
                    placeName.append(place.getPlaceName());
                }
            }
            vo.setPosition(placeName.toString());
            AppSensor appSensor = new AppSensor();
            appSensor.setDeviceId(appDevice.getDeviceId());
            List<AppFault> faultList = appFaultService.selectUnCheckedAppFaultListByDeviceId(appDevice.getDeviceId());
            String alarm = "";
            Map<Long, AppFault> faultMap = new HashedMap<>();
            for (AppFault appFault : faultList) {
                AppFault fault = faultMap.get(appFault.getFaultRuleId());
                if (fault == null) {
                    faultMap.put(appFault.getFaultRuleId(), appFault);
                } else if (appFault.getCreateTime().compareTo(fault.getCreateTime()) > 0) {
                    faultMap.put(appFault.getFaultRuleId(), appFault);
                }
            }
            List<String> alarmList = new ArrayList<>();
            for (Long key : faultMap.keySet()) {
                AppFault fault = faultMap.get(key);
                if (fault != null) {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String dateStr = simpleDateFormat.format(fault.getCreateTime());
                    alarm += fault.getFaultName() + ":" + dateStr;
                    alarm = vo.getDeviceName() + ":" + alarm;
                    alarmList.add(alarm);
                }
            }
            vo.setAlarmContent(alarmList);
            List<AppSensor> sensorList = sensorService.selectAppSensorAllListByDeviceId(appSensor.getDeviceId());
            List<AppSensor> powerStatusSensorList = new ArrayList<>();
            if (!sensorList.isEmpty()) {
                for (AppSensor sensor : sensorList) {
//                    AppSensor s = mongoTemplate.findById(sensor.getSensorId(), AppSensor.class);
                    String s = null;
                    try {
                        Object object = redisTemplate.opsForValue().get(CacheConstants.APP_SENSOR_VALUE_KEY + sensor.getDeviceId() + ":sensorId:" + sensor.getSensorId());
                        if (object != null) {
                            if (object instanceof String) {
                                s = (String) object;
                            } else if (object instanceof BigDecimal) {
                                s = ((BigDecimal) object).toString();
                            } else {
                                System.out.println(object.toString());
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        System.out.println(CacheConstants.APP_SENSOR_VALUE_KEY + sensor.getDeviceId() + ":sensorId:" + sensor.getSensorId());
                    }
                    if (s != null) {
                        if (sensor.getSensorType().equals("4")) {
                            vo.setAirVolume(s);
                        } else if (sensor.getSensorType().equals("9")) {
                            vo.setAirSpeed(s);
                        } else if (sensor.getSensorType().equals("8") && sensor.getIsHeight() != null && sensor.getIsHeight().equals("1")) {
                            vo.setWindowHeight(s);
                        } else if (sensor.getSensorType().equals("13")) {
                            vo.setAngle(s);
                        } else if (sensor.getSensorType().equals("2")) {
                            vo.setHumidity(s);
                        } else if (sensor.getSensorType().equals("1")) {
                            vo.setTemperature(s);
                        } else if (sensor.getSensorType().equals("3")) {
                            vo.setPressure(s);
                        } else if (sensor.getSensorType().equals("6")) {
                            vo.setPowerConsumption(s);
                        } else if (sensor.getSensorType().equals("10")) {
                            vo.setFrequency(s);
                        } else if (sensor.getSensorType().equals("11")) {
                            vo.setAmpere(s);
                        } else if (sensor.getSensorType().equals("16")) {
                            vo.setTvoc(s);
                        } else if (sensor.getSensorType().equals("21")) {
                            vo.setCH2O(s);
                        } else if (sensor.getSensorType().equals("23")) {
                            vo.setO2(s);
                        } else if (sensor.getSensorType().equals("15")) {
                            vo.setNoise(s);
                        } else if (sensor.getSensorType().equals("14")) {
                            vo.setIllumination(s);
                        } else if (sensor.getSensorType().equals("20")) {
                            vo.setCO2(s);
                        } else if (sensor.getSensorType().equals("19")) {
                            vo.setPM1(s);
                        } else if (sensor.getSensorType().equals("18")) {
                            vo.setPM10(s);
                        } else if (sensor.getSensorType().equals("17")) {
                            vo.setPM2Point5(s);
                        } else if (sensor.getSensorType().equals("25")) {
                            vo.setRawWaterConductivity(s);
                        } else if (sensor.getSensorType().equals("26")) {
                            vo.setFirstWaterConductivity(s);
                        } else if (sensor.getSensorType().equals("27")) {
                            vo.setSecondWaterConductivity(s);
                        } else if (sensor.getSensorType().equals("28")) {
                            vo.setLiquidLevel(s);
                        } else if (sensor.getUnit().equals("开关量")) {
                            if (StringUtils.endsWith(s, ".0")) {
                                s = StringUtils.substringBefore(s, ".0");
                            }
                            if (sensor.getIsLight() != null && sensor.getIsLight().equals("1")) {
                                vo.setLight(s);
                            } else if (sensor.getIsForce() != null && sensor.getIsForce().equals("1")) {
                                vo.setForce(s);
                            } else if (sensor.getIsOn() != null && sensor.getIsOn().equals("1")) {
                                vo.setPower(s);
                            } else if (sensor.getIsAutoDoor() != null && sensor.getIsAutoDoor().equals("1")) {
                                vo.setIsAutoDoor(s);
                            } else if (sensor.getIsBeing() != null && sensor.getIsBeing().equals("1")) {
                                vo.setIsBeing(s);
                            } else if (sensor.getWorkMode() != null && sensor.getWorkMode().equals("1")) {
                                vo.setWorkingMode(s);
                            }
                        }
                    }
                    if (sensor.getSensorType().equals("24")) {
                        powerStatusSensorList.add(sensor);
                    } else if (sensor.getSensorType().equals("22") && sensor.getIsOn() != null && sensor.getIsOn().equals("1") && vo.getPower() == null) {
                        vo.setPower("0");
                        vo.setIsRunning("0");
                        vo.setIsOnline("0");
                    }
                    sensor.setValue(s);
                }
            }
            if (!powerStatusSensorList.isEmpty()) {
                for (AppSensor sensor : powerStatusSensorList) {
                    if (sensor.getValue() != null && !sensor.getValue().trim().equals("")) {
                        if (StringUtils.endsWith(sensor.getValue(), ".0")) {
                            String val = StringUtils.substringBefore(sensor.getValue(), ".0");
                            sensor.setValue(val);
                        }
                        vo.setPower(sensor.getValue());
                    }
                }
            }
            voList.add(vo);
        }
        return AjaxResult.success(voList);
    }

    /**
     * 获取用户信息
     *
     * @param
     * @return
     */
    @ApiOperation(value = "获取设备信息")
    @PostMapping("/deviceWx")
    public AjaxResult getDeviceWx(@RequestBody Long[] ids) {
        long startTime = System.nanoTime();
        System.out.println("请求开始" + System.nanoTime());
        List<DeviceVO> voList = new ArrayList<>();
        for (Long deviceId : ids) {
            DeviceVO vo = new DeviceVO();
            vo.setDeviceId(deviceId);
            long sTime = System.nanoTime();
            System.out.println("开始获取告警数据" + System.nanoTime());
            List<AppFault> faultList = appFaultService.selectUnCheckedAppFaultListByDeviceId(deviceId);
            sTime = System.nanoTime();
            System.out.println("获取告警数据结束" + (System.nanoTime() - sTime));
            String alarm = "";
            Map<Long, AppFault> faultMap = new HashedMap<>();
            for (AppFault appFault : faultList) {
                AppFault fault = faultMap.get(appFault.getFaultRuleId());
                if (fault == null) {
                    faultMap.put(appFault.getFaultRuleId(), appFault);
                } else if (appFault.getCreateTime().compareTo(fault.getCreateTime()) > 0) {
                    faultMap.put(appFault.getFaultRuleId(), appFault);
                }
            }
            List<String> alarmList = new ArrayList<>();
            for (Long key : faultMap.keySet()) {
                AppFault fault = faultMap.get(key);
                if (fault != null) {
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String dateStr = simpleDateFormat.format(fault.getCreateTime());
                    alarm += fault.getFaultName() + ":" + dateStr;
                    AppDevice appDevice = deviceService.selectAppDeviceByDeviceId(deviceId);
                    if (appDevice != null) {
                        vo.setDeviceName(appDevice.getDeviceName());
                        alarm = vo.getDeviceName() + ":" + alarm;
                    }
                    alarmList.add(alarm);
                }
            }
            vo.setAlarmContent(alarmList);
            sTime = System.nanoTime();
            System.out.println("告警数据处理结束" + (System.nanoTime() - sTime));
            List<AppSensor> sensorList = sensorService.selectAppSensorAllListByDeviceId(deviceId);
            sTime = System.nanoTime();
            System.out.println("请求传感器数据结束" + (System.nanoTime() - sTime));
            List<AppSensor> powerStatusSensorList = new ArrayList<>();
            if (!sensorList.isEmpty()) {
                for (AppSensor sensor : sensorList) {
//                    AppSensor s = mongoTemplate.findById(sensor.getSensorId(), AppSensor.class);
                    String s = null;
                    Object object = redisTemplate.opsForValue().get(CacheConstants.APP_SENSOR_VALUE_KEY + sensor.getDeviceId() + ":sensorId:" + sensor.getSensorId());
                    if (object != null) {
                        if (object instanceof String) {
                            s = object.toString();
                        }
                        if (object instanceof BigDecimal) {
                            s = ((BigDecimal) object).toString();
                        }
                    }
                    if (s != null) {
                        if (sensor.getSensorType().equals("4")) {
                            vo.setAirVolume(s);
                        } else if (sensor.getSensorType().equals("9")) {
                            vo.setAirSpeed(s);
                        } else if (sensor.getSensorType().equals("8") && sensor.getIsHeight() != null && sensor.getIsHeight().equals("1")) {
                            vo.setWindowHeight(s);
                        } else if (sensor.getSensorType().equals("13")) {
                            vo.setAngle(s);
                        } else if (sensor.getSensorType().equals("2")) {
                            vo.setHumidity(s);
                        } else if (sensor.getSensorType().equals("1")) {
                            vo.setTemperature(s);
                        } else if (sensor.getSensorType().equals("3")) {
                            vo.setPressure(s);
                        } else if (sensor.getSensorType().equals("6")) {
                            vo.setPowerConsumption(s);
                        } else if (sensor.getSensorType().equals("10")) {
                            vo.setFrequency(s);
                        } else if (sensor.getSensorType().equals("11")) {
                            vo.setAmpere(s);
                        } else if (sensor.getSensorType().equals("16")) {
                            vo.setTvoc(s);
                        } else if (sensor.getSensorType().equals("21")) {
                            vo.setCH2O(s);
                        } else if (sensor.getSensorType().equals("23")) {
                            vo.setO2(s);
                        } else if (sensor.getSensorType().equals("15")) {
                            vo.setNoise(s);
                        } else if (sensor.getSensorType().equals("14")) {
                            vo.setIllumination(s);
                        } else if (sensor.getSensorType().equals("20")) {
                            vo.setCO2(s);
                        } else if (sensor.getSensorType().equals("19")) {
                            vo.setPM1(s);
                        } else if (sensor.getSensorType().equals("18")) {
                            vo.setPM10(s);
                        } else if (sensor.getSensorType().equals("17")) {
                            vo.setPM2Point5(s);
                        } else if (sensor.getSensorType().equals("25")) {
                            vo.setRawWaterConductivity(s);
                        } else if (sensor.getSensorType().equals("26")) {
                            vo.setFirstWaterConductivity(s);
                        } else if (sensor.getSensorType().equals("27")) {
                            vo.setSecondWaterConductivity(s);
                        } else if (sensor.getSensorType().equals("28")) {
                            vo.setLiquidLevel(s);
                        } else if (sensor.getUnit().equals("开关量")) {
                            if (s != null) {
                                if (StringUtils.endsWith(s, ".0")) {
                                    String val = StringUtils.substringBefore(s, ".0");
                                    s = val;
                                }
                            }
                            if (sensor.getIsLight() != null && sensor.getIsLight().equals("1")) {
                                vo.setLight(s);
                            } else if (sensor.getIsForce() != null && sensor.getIsForce().equals("1")) {
                                vo.setForce(s);
                            } else if (sensor.getIsOn() != null && sensor.getIsOn().equals("1")) {
                                vo.setPower(s);
                            } else if (sensor.getIsAutoDoor() != null && sensor.getIsAutoDoor().equals("1")) {
                                vo.setIsAutoDoor(s);
                            } else if (sensor.getIsBeing() != null && sensor.getIsBeing().equals("1")) {
                                vo.setIsBeing(s);
                            } else if (sensor.getWorkMode() != null && sensor.getWorkMode().equals("1")) {
                                vo.setWorkingMode(s);
                            }
                        }
                        sensor.setValue(s);
                    }
                    if (sensor.getSensorType().equals("24")) {
                        powerStatusSensorList.add(sensor);
                    } else if (sensor.getSensorType().equals("22") && sensor.getIsOn() != null && sensor.getIsOn().equals("1") && vo.getPower() == null) {
                        vo.setPower("0");
                        vo.setIsRunning("0");
                        vo.setIsOnline("0");
                    }
                }
            }
            if (powerStatusSensorList.size() > 0) {
                for (AppSensor sensor : powerStatusSensorList) {
                    if (sensor.getValue() != null && !sensor.getValue().trim().equals("")) {
                        if (StringUtils.endsWith(sensor.getValue(), ".0")) {
                            String val = StringUtils.substringBefore(sensor.getValue(), ".0");
                            sensor.setValue(val);
                        }
                        vo.setPower(sensor.getValue());
                    }
                }
            }
            voList.add(vo);
            System.out.println("传感器数据处理结束" + (System.nanoTime() - startTime));
        }
        System.out.println("请求结束" + (System.nanoTime() - startTime));
        return AjaxResult.success(voList);
    }


    @GetMapping("/getDevice")
    public AjaxResult getDeviceById(String deviceId) throws Exception {
        if (deviceId != null) {
            Long id = Long.parseLong(deviceId);
            AppDevice appDevice = deviceService.selectAppDeviceByDeviceId(id); //根据Id获取设备详情
            List<AppDevice> appDeviceList = deviceService.selectChildrenAppDeviceById(id); //获取本设备下的下级设备
            appDevice.setChildren(appDeviceList);
            DeviceVO vo = getVO(appDevice);
            getList(vo, appDevice);
            if (vo.getType().equals("1")) {
                List<DeviceVO> voList = vo.getChildrenVO();
                List<AppSensor> list = vo.getSensorList();
                if (voList != null) {
                    for (DeviceVO deviceVO : voList) {
                        list.addAll(deviceVO.getSensorList());
                    }
                }
                vo.setSensorList(list);
            }
            List<Long> adminIds = deviceService.selectAppDeviceAdminListByDeviceId(vo.getDeviceId()); //获取设备的管理员
            if (adminIds.contains(SecurityUtils.getUserId())) {
                vo.setIsAdmin("1");
            }
            List<Long> operatorIds = deviceService.selectAppDeviceOperatorListByDeviceId(id); //获取设备的操作员
            if (operatorIds.contains(SecurityUtils.getUserId())) {
                vo.setIsOperator("1");
            }
            return AjaxResult.success(vo);
        }
        return AjaxResult.error();
    }

    private void getList(DeviceVO vo, AppDevice appDevice) throws Exception {
        List<AppDevice> appDeviceList = deviceService.selectChildrenAppDeviceById(appDevice.getDeviceId()); //获取设备的下级设备
        if (appDeviceList != null && !appDeviceList.isEmpty()) {
            List<DeviceVO> voList = new ArrayList<>();
            for (AppDevice device : appDeviceList) {
                DeviceVO v = getVO(device);
                voList.add(v);
                getList(v, device);
            }
            vo.setChildrenVO(voList);
        }
    }

    private DeviceVO getVO(AppDevice appDevice) throws Exception {
        DeviceVO vo = new DeviceVO();
        BeanUtils.copyProperties(vo, appDevice);
        List<Long> placeIds = deviceService.selectAppDevicePlaceListByDeviceId(appDevice.getDeviceId()); //获取设备位置
        StringBuilder placeName = new StringBuilder();
        for (Long placeId : placeIds) {
            SysPlace place = placeService.selectPlaceById(placeId);
            if (place != null) {
                placeName.append(place.getPlaceName());
            }
        }
        List<Long> userIds = deviceService.selectAdminPhoneByDeviceId(appDevice.getDeviceId()); //获取设备管理员用户
        List<SysUser> phones = new ArrayList<>();
        for (Long userId : userIds) {
            SysUser sysUser = sysUserService.selectUserById(userId);
            if (sysUser != null) {
                phones.add(sysUser);
            }
        }
        vo.setPosition(placeName.toString());
        vo.setPhone(phones);
        List<AppFault> faultList = appFaultService.selectUnCheckedAppFaultListByDeviceId(appDevice.getDeviceId()); //获取设备告警列表
        Map<Long, AppFault> faultMap = new HashedMap<>();
        for (AppFault appFault : faultList) {
            AppFault fault = faultMap.get(appFault.getFaultRuleId());
            if (fault == null) {
                faultMap.put(appFault.getFaultRuleId(), appFault);
            } else if (appFault.getCreateTime().compareTo(fault.getCreateTime()) > 0) {
                faultMap.put(appFault.getFaultRuleId(), appFault);
            }
        }
        List<String> alarmList = new ArrayList<>();
        for (Long key : faultMap.keySet()) {
            AppFault fault = faultMap.get(key);
            if (fault != null) {
                String alarm = "";
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String dateStr = simpleDateFormat.format(fault.getCreateTime());
                alarm += fault.getFaultName() + ":" + dateStr;
//                alarm = vo.getDeviceName() + ":" + alarm;
                alarmList.add(alarm);
            }
        }
        vo.setAlarmContent(alarmList);
        AppSensor appSensor = new AppSensor();
        appSensor.setDeviceId(appDevice.getDeviceId());
        List<AppSensor> sensorList = sensorService.selectAppSensorAllListByDeviceIdForApp(appDevice.getDeviceId()); //获取设备的传感器列表
        List<AppSensor> powerStatusSensorList = new ArrayList<>();
        List<AppSensor> appSensorLis = new ArrayList<>();
        if (!sensorList.isEmpty()) {
            for (AppSensor sensor : sensorList) {
                String s = null;
                Object object = redisTemplate.opsForValue().get(CacheConstants.APP_SENSOR_VALUE_KEY + sensor.getDeviceId() + ":sensorId:" + sensor.getSensorId());
                if (object != null) {
                    if (object instanceof String) {
                        s = object.toString();
                    }
                    if (object instanceof BigDecimal) {
                        s = ((BigDecimal) object).toString();
                    }
                }
                if (s != null) {
                    if (sensor.getSensorType().equals("4")) {
                        vo.setAirVolume(s);
                    } else if (sensor.getSensorType().equals("9")) {
                        vo.setAirSpeed(s);
                    } else if (sensor.getSensorType().equals("8") && sensor.getIsHeight() != null && sensor.getIsHeight().equals("1")) {
                        vo.setWindowHeight(s);
                    } else if (sensor.getSensorType().equals("13")) {
                        vo.setAngle(s);
                    } else if (sensor.getSensorType().equals("2")) {
                        vo.setHumidity(s);
                    } else if (sensor.getSensorType().equals("1")) {
                        vo.setTemperature(s);
                    } else if (sensor.getSensorType().equals("3")) {
                        vo.setPressure(s);
                    } else if (sensor.getSensorType().equals("6")) {
                        vo.setPowerConsumption(s);
                    } else if (sensor.getSensorType().equals("10")) {
                        vo.setFrequency(s);
                    } else if (sensor.getSensorType().equals("11")) {
                        vo.setAmpere(s);
                    } else if (sensor.getSensorType().equals("16")) {
                        vo.setTvoc(s);
                    } else if (sensor.getSensorType().equals("21")) {
                        vo.setCH2O(s);
                    } else if (sensor.getSensorType().equals("23")) {
                        vo.setO2(s);
                    } else if (sensor.getSensorType().equals("15")) {
                        vo.setNoise(s);
                    } else if (sensor.getSensorType().equals("14")) {
                        vo.setIllumination(s);
                    } else if (sensor.getSensorType().equals("20")) {
                        vo.setCO2(s);
                    } else if (sensor.getSensorType().equals("19")) {
                        vo.setPM1(s);
                    } else if (sensor.getSensorType().equals("18")) {
                        vo.setPM10(s);
                    } else if (sensor.getSensorType().equals("17")) {
                        vo.setPM2Point5(s);
                    } else if (sensor.getSensorType().equals("25")) {
                        vo.setRawWaterConductivity(s);
                    } else if (sensor.getSensorType().equals("26")) {
                        vo.setFirstWaterConductivity(s);
                    } else if (sensor.getSensorType().equals("27")) {
                        vo.setSecondWaterConductivity(s);
                    } else if (sensor.getSensorType().equals("28")) {
                        vo.setLiquidLevel(s);
                    } else if (sensor.getUnit().equals("开关量")) {
                        if (s != null) {
                            if (StringUtils.endsWith(s, ".0")) {
                                String val = StringUtils.substringBefore(s, ".0");
                                s = val;
                            }
                        }
                        if (sensor.getIsLight() != null && sensor.getIsLight().equals("1")) {
                            vo.setLight(s);
                        } else if (sensor.getIsForce() != null && sensor.getIsForce().equals("1")) {
                            vo.setForce(s);
                        } else if (sensor.getIsOn() != null && sensor.getIsOn().equals("1")) {
                            vo.setPower(s);
                            sensor.setValue(s);
                        } else if (sensor.getIsAutoDoor() != null && sensor.getIsAutoDoor().equals("1")) {
                            vo.setIsAutoDoor(s);
                        } else if (sensor.getIsBeing() != null && sensor.getIsBeing().equals("1")) {
                            vo.setIsBeing(s);
                        } else if (sensor.getWorkMode() != null && sensor.getWorkMode().equals("1")) {
                            vo.setWorkingMode(s);
                        }
                    }
                    sensor.setValue(s);
                } else {
                    sensor.setValue(s);
                }
                if (sensor.getSensorType().equals("24")) {
                    powerStatusSensorList.add(sensor);
                } else if (sensor.getSensorType().equals("22") && sensor.getIsOn() != null && sensor.getIsOn().equals("1") && vo.getPower() == null) {
                    vo.setPower("0");
                    vo.setIsRunning("0");
                    vo.setIsOnline("0");
                    sensor.setValue("0");
                }
                appSensorLis.add(sensor);
            }
        }
        if (powerStatusSensorList.size() > 0) {
            for (AppSensor sensor : powerStatusSensorList) {
                if (sensor.getValue() != null && !sensor.getValue().trim().equals("")) {
                    if (StringUtils.endsWith(sensor.getValue(), ".0")) {
                        String val = StringUtils.substringBefore(sensor.getValue(), ".0");
                        sensor.setValue(val);
                    }
                    vo.setPower(sensor.getValue());
                } else {
                    vo.setPower("0");
                }
            }
        }
        vo.setSensorList(appSensorLis);
        return vo;
    }

    @PostMapping("/updateDevice")
    public AjaxResult updateDeviceById(@RequestBody DeviceVO device) throws Exception {
        if (device != null && device.getDeviceId() != null) {
            AppSensor appSensor = new AppSensor();
            if (device.getCommandKey() != null) {
                switch (device.getCommandKey()) {
                    case "light":
                        appSensor.setIsLight("1");
                        break;
                    case "power":
                        appSensor.setIsOn("1");
                        break;
                    case "force":
                        appSensor.setIsForce("1");
                        break;
                    case "windowHeight":
                        appSensor.setIsHeight("1");
                        break;
                    case "mode":
                        appSensor.setWorkMode("1");
                        break;
                    case "isAutoDoor":
                        appSensor.setIsAutoDoor("1");
                        break;
                }
            }
            appSensor.setDeviceId(device.getDeviceId());
            List<AppSensor> sensorList = sensorService.selectAppSensorAllList(appSensor);
            if (sensorList != null && !sensorList.isEmpty()) {
                AppSensor sensor = sensorList.get(0);
                sensor.setValue(device.getCommandValue());
                sensorService.updateAppSensorStatus(sensor);
            }
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    @PostMapping("/updateSensor")
    public AjaxResult updateSensor(@RequestBody List<AppSensor> sensorList) {
        if (sensorList != null && !sensorList.isEmpty()) {
            for (AppSensor sensor : sensorList) {
                sensorService.updateAppSensorStatus(sensor);
            }
            return AjaxResult.success();
        }
        return AjaxResult.error();
    }

    @GetMapping("/getAlarm")
    public AjaxResult getAlarm(String orderLevel, String orderTime) {
        String userName = SecurityUtils.getUsername();
        SysUser sysUser = sysUserService.selectUserByUserName(userName);
        List<List<AppFault>> vo = new LinkedList<>();
        if (sysUser.getPhonenumber() != null) {
            List<AppDevice> deviceList = deviceService.selectDeviceListByUserId(sysUser.getUserId());
            Set<Long> set = new HashSet<>();
            for (AppDevice device : deviceList) {
                set.add(device.getDeviceId());
            }
            List<AppFault> readFaultList = faultService.selectAppFaultByDeviceIds(set, sysUser.getUserId(), "1", orderLevel, orderTime);
            List<AppFault> unreadFaultList = faultService.selectAppFaultByDeviceIds(set, sysUser.getUserId(), "0", orderLevel, orderTime);

            vo.add(unreadFaultList);
            vo.add(readFaultList);
        }
        return AjaxResult.success(vo);
    }

    @GetMapping("/updateAlarmRead")
    public AjaxResult updateAlarmRead(Long faultId) {
        String userName = SecurityUtils.getUsername();
        SysUser sysUser = sysUserService.selectUserByUserName(userName);
        if (sysUser.getPhonenumber() != null) {
            AppFaultRead faultRead = new AppFaultRead();
            faultRead.setFaultId(faultId);
            faultRead.setUserId(sysUser.getUserId());
            List<AppFaultRead> list = faultReadService.selectAppFaultReadList(faultRead);
            if (list == null || list.size() == 0) {
                faultRead.setUpdateBy(sysUser.getUserName());
                faultRead.setUpdateTime(new Date());
                faultRead.setCreateBy(sysUser.getUserName());
                faultRead.setCreateTime(new Date());
                faultReadService.insertAppFaultRead(faultRead);
            }
        }
        return AjaxResult.success();
    }

    @GetMapping("/updateAllAlarmRead")
    public AjaxResult updateAllAlarmRead(Long[] faultIds) {
        String userName = SecurityUtils.getUsername();
        SysUser sysUser = sysUserService.selectUserByUserName(userName);
        if (sysUser.getUserId() != null) {
            AppFaultRead faultRead = new AppFaultRead();
            for (Long faultId : faultIds) {
                faultRead.setFaultId(faultId);
                faultRead.setUserId(sysUser.getUserId());
                List<AppFaultRead> list = faultReadService.selectAppFaultReadList(faultRead);
                if (list == null || list.isEmpty()) {
                    faultRead.setUpdateBy(sysUser.getUserName());
                    faultRead.setUpdateTime(new Date());
                    faultRead.setCreateBy(sysUser.getUserName());
                    faultRead.setCreateTime(new Date());
                    faultReadService.insertAppFaultRead(faultRead);
                }
            }
        }
        return AjaxResult.success();
    }

    @GetMapping("/getAlarmDetail")
    public AjaxResult getAlarmDetail(Long faultId) {
        AppFault fault = faultService.selectAppFaultByFaultId(faultId);
        AppFaultVO vo = new AppFaultVO();
        BeanUtil.copyProperties(fault, vo);
        if (vo.getDeviceId() != null) {
            AppDevice appDevice = deviceService.selectAppDeviceByDeviceId(vo.getDeviceId());
            vo.setAppDevice(appDevice);
        }
        if (vo.getSensorId() != null) {
            AppSensor appSensor = sensorService.selectAppSensorBySensorId(vo.getSensorId());
            vo.setAppSensor(appSensor);
        }
        if (vo.getFaultRuleId() != null) {
            AppFaultRule appFaultRule = faultRuleService.selectAppFaultRuleByFaultRuleId(vo.getFaultRuleId());
            vo.setAppFaultRule(appFaultRule);
        }
        AppFaultHandle faultHandle = faultHandleService.selectAppFaultHandleByFaultId(faultId);
        vo.setFaultHandle(faultHandle);
        if (faultHandle != null && faultHandle.getHandleId() != null) {
            AppFaultHandleRecord record = new AppFaultHandleRecord();
            record.setHandleId(faultHandle.getHandleId());
            List<AppFaultHandleRecord> faultHandleRecordList = faultHandleRecordService.selectAppFaultHandleRecordList(record);
            vo.setHandleRecordList(faultHandleRecordList);
        }
        return AjaxResult.success(vo);
    }

    @PostMapping("/dismissAlarm")
    public AjaxResult dismissAlarm(@RequestBody FaultHandleDto faultHandleDto) {
        AppFaultHandle faultHandle = faultHandleService.selectAppFaultHandleByFaultId(faultHandleDto.getFaultId());
        if (faultHandle == null) {
            faultHandle = new AppFaultHandle();
            faultHandle.setFaultId(faultHandleDto.getFaultId());
        }
        faultHandle.setHandleRecord(faultHandleDto.getRecord());
        faultHandle.setIsChecked(faultHandleDto.getIsDismiss());
        String userName = SecurityUtils.getUsername();
        SysUser sysUser = sysUserService.selectUserByUserName(userName);
        faultHandle.setUserId(sysUser.getUserId());
        if (faultHandle.getHandleId() == null) {
            faultHandle.setCreateBy(sysUser.getUserName());
            faultHandle.setCreateTime(DateUtils.getNowDate());
        }
        faultHandle.setUpdateTime(DateUtils.getNowDate());
        faultHandle.setUpdateBy(sysUser.getUserName());
        if (faultHandle.getHandleId() == null) {
            faultHandleService.insertAppFaultHandle(faultHandle);
            AppFaultHandleRecord faultHandleRecord = new AppFaultHandleRecord();
            faultHandleRecord.setHandleId(faultHandle.getHandleId());
            faultHandleRecord.setHandleRecord(faultHandleDto.getRecord());
            faultHandleRecord.setUpdateBy(faultHandle.getUpdateBy());
            faultHandleRecord.setCreateBy(faultHandle.getCreateBy());
            faultHandleRecord.setCreateTime(new Timestamp(new Date().getTime()));
            faultHandleRecord.setUpdateTime(new Timestamp(new Date().getTime()));
            faultHandleRecord.setUserId(faultHandle.getUserId());
            faultHandleRecordService.insertAppFaultHandleRecord(faultHandleRecord);
        } else {
            faultHandleService.updateAppFaultHandle(faultHandle);
        }
        return AjaxResult.success();
    }


    @GetMapping("/allDismissAlarm")
    public AjaxResult allDismissAlarm() {
        String userName = SecurityUtils.getUsername();
        SysUser sysUser = sysUserService.selectUserByUserName(userName);
        if (sysUser.getUserId() != null) {
            List<AppDevice> deviceList = deviceService.selectDeviceListByUserId(sysUser.getUserId());
            Set<Long> set = new HashSet<>();
            for (AppDevice device : deviceList) {
                set.add(device.getDeviceId());
            }
            List<AppFault> faultList = faultService.selectUnCheckedAppFaultListByDeviceIds(set);
            for (AppFault fault : faultList) {
                AppFaultHandle faultHandle = faultHandleService.selectAppFaultHandleByFaultId(fault.getFaultId());
                if (faultHandle == null) {
                    faultHandle = new AppFaultHandle();
                    faultHandle.setFaultId(fault.getFaultId());
                }
                faultHandle.setHandleRecord("全部消警");
                faultHandle.setIsChecked("1");
                if (faultHandle.getHandleId() == null) {
                    faultHandle.setCreateBy(sysUser.getUserName());
                    faultHandle.setCreateTime(DateUtils.getNowDate());
                }
                faultHandle.setUpdateTime(DateUtils.getNowDate());
                faultHandle.setUpdateBy(sysUser.getUserName());
                if (faultHandle.getHandleId() == null) {
                    faultHandleService.insertAppFaultHandle(faultHandle);
                    AppFaultHandleRecord faultHandleRecord = new AppFaultHandleRecord();
                    faultHandleRecord.setHandleId(faultHandle.getHandleId());
                    faultHandleRecord.setHandleRecord("全部消警");
                    faultHandleRecord.setUpdateBy(faultHandle.getUpdateBy());
                    faultHandleRecord.setCreateBy(faultHandle.getCreateBy());
                    faultHandleRecord.setCreateTime(new Timestamp(new Date().getTime()));
                    faultHandleRecord.setUpdateTime(new Timestamp(new Date().getTime()));
                    faultHandleRecord.setUserId(faultHandle.getUserId());
                    faultHandleRecordService.insertAppFaultHandleRecord(faultHandleRecord);
                } else {
                    faultHandleService.updateAppFaultHandle(faultHandle);
                }
            }
        }
        return AjaxResult.success();
    }

    //    @PostMapping("/feedback")
//    public AjaxResult addFeedback(@RequestBody AppFeedBack feedBack) {
//        String userName = SecurityUtils.getUsername();
//        SysUser sysUser = sysUserService.selectUserByUserName(userName);
//        if (sysUser != null) {
//            feedBack.setOpenId(sysUser.getUserName());
//            feedBack.setNickName(sysUser.getNickName());
//            feedBack.setIsCommon("0");
//            feedBack.setCreateTime(new Timestamp(new Date().getTime()));
//            feedBack.setUpdateTime(new Timestamp(new Date().getTime()));
//            if (feedBack.getFeedImg() != null && StringUtils.endsWith(feedBack.getFeedImg(), ".0")) {
//                String s = feedBack.getFeedImg();
//                feedBack.setFeedImg(StringUtils.substringBefore(s, ".0"));
//            }
//            return AjaxResult.success(feedBackService.insertAppFeedBack(feedBack));
//        }
//        return AjaxResult.error();
//    }
//
//    @GetMapping("/myFeedback")
//    public AjaxResult myFeedback() {
//        String userName = SecurityUtils.getUsername();
//        SysUser sysUser = sysUserService.selectUserByUserName(userName);
//        if (sysUser != null) {
//            AppFeedBack feedBack = new AppFeedBack();
//            feedBack.setOpenId(sysUser.getUserName());
//            List<AppFeedBack> list = feedBackService.selectAppFeedBackList(feedBack);
//            return AjaxResult.success(list);
//        }
//        return AjaxResult.error();
//    }
//
//    @GetMapping("/commonFeedback")
//    public AjaxResult commonFeedback() {
//        AppFeedBack feedBack = new AppFeedBack();
//        feedBack.setIsCommon("1");
//        List<AppFeedBack> list = feedBackService.selectAppFeedBackList(feedBack);
//        return AjaxResult.success(list);
//    }
//
    @PostMapping("/oneKeyRepairApp")
    public AjaxResult oneKeyRepairApp(@RequestBody AppOneKeyRepair appOneKeyRepair) {
        String userName = SecurityUtils.getUsername();
        SysUser sysUser = sysUserService.selectUserByUserName(userName);
        if (sysUser != null) {
            appOneKeyRepair.setOpenId(sysUser.getUserName());
            appOneKeyRepair.setNickName(sysUser.getNickName());
            appOneKeyRepair.setPhone(sysUser.getPhonenumber());
            appOneKeyRepair.setCreateBy(sysUser.getNickName());
            appOneKeyRepair.setCreateTime(DateUtils.getNowDate());
            return AjaxResult.success(oneKeyRepairService.insertAppOneKeyRepair(appOneKeyRepair));
        }
        return AjaxResult.error("无用户信息");
    }

    //
//    @GetMapping("/deviceModel")
//    public AjaxResult getDeviceModel(String modelCode) {
//        AppDeviceModel appDeviceModel = appDeviceModelService.selectAppDeviceModelByModelCode(modelCode);
//        if (appDeviceModel != null) {
//            AppDeviceModelDto deviceModelDto = new AppDeviceModelDto();
//            BeanUtil.copyProperties(appDeviceModel, deviceModelDto);
//            AppDeviceDocument deviceDocument = new AppDeviceDocument();
//            deviceDocument.setModelId(appDeviceModel.getModelId());
//            List<AppDeviceDocument> files = appDeviceDocumentService.selectAppDeviceDocumentList(deviceDocument);
//            List<AppDeviceDocument> fileList = new ArrayList<>();
//            List<AppDeviceDocument> videoList = new ArrayList<>();
//            for (AppDeviceDocument document : files) {
//                if (document.getFileType() != null && document.getFileType().contains("mp4")) {
//                    videoList.add(document);
//                } else if (document.getFileType() != null && document.getFileType().contains("pdf")) {
//                    fileList.add(document);
//                }
//            }
//            deviceModelDto.setVideoList(videoList);
//            deviceModelDto.setFileList(fileList);
//            String type = deviceModelDto.getModelType();
//            if (type != null) {
//                String deviceType =  sysDictDataService.selectDictLabel("app_device_type", type);
//                deviceModelDto.setModelType(deviceType);
//            }
//            return AjaxResult.success(deviceModelDto);
//        }
//        return AjaxResult.error("无设备型号信息");
//    }
//
    @GetMapping("/document")
    public AjaxResult getDocument(Long documentId) {
        AppDeviceDocument appDeviceDocument = appDeviceDocumentService.selectAppDeviceDocumentByDocumentId(documentId);
        return AjaxResult.success(appDeviceDocument);
    }

    @PostMapping("/defFaultRule")
    public AjaxResult updateSensorFaultRule(@RequestBody AppSensor sensor) {
        AppFaultRule faultRule = sensor.getFaultRule();
        if (faultRule.getRuleName() != null && faultRule.getRuleValueBottomlimit() != null && faultRule.getRuleValueBottomlimit() != null) {
            faultRuleService.insertAppFaultRule(faultRule);
            sensor.setFaultRuleId(faultRule.getFaultRuleId());
            sensor.setFaultRule(faultRule);
            sensorService.updateAppSensorFault(sensor);
            sensor = sensorService.selectAppSensorBySensorId(sensor.getSensorId());
            return AjaxResult.success(sensor);
        } else {
            return AjaxResult.error("更新失败");
        }
    }

    @GetMapping("/project/version")
    public AjaxResult getProjectVersion(String projectCode){
        AppProject project = appProjectService.selectAppProjectByProjectCode(projectCode);
        if (project != null){
            AppProject appProject = new AppProject();
            appProject.setProjectId(project.getProjectId());
            appProject.setProjectCode(projectCode);
            appProject.setProjectImage(project.getProjectImage());
            appProject.setAppVersion(project.getAppVersion());
            appProject.setAppFile(project.getAppFile());
            return AjaxResult.success(appProject);
        }
        return AjaxResult.error();
    }
}
